package edu.intprog.egreeting;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import edu.intprog.sql.SessionManager;
import edu.intprog.egreeting.basic.EgreetingBaseServlet;
import edu.intprog.egreeting.beans.GreetingHistory;
import edu.intprog.egreeting.beans.Messages;
import edu.intprog.egreeting.beans.UserDef;

/**
 * Servlet implementation class for Servlet: ViewHistoryServlet
 *
 */
 public class ViewHistoryServlet extends EgreetingBaseServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public ViewHistoryServlet() {
		super();
	}   	 	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
		UserDef user = (UserDef) request.getSession().getAttribute("user");
		if (user==null)
		{
			//simple security measure
			getServletContext().getRequestDispatcher("/StartServlet").forward(request, response);
			return;
		}
		
		//get all of the greetings that were sent or received by the user
		//from the greeting history table
		Transaction tx = null;
		Session session = SessionManager.getCurrentSession();
		List<GreetingHistory> userHistory = null;
		try {
			tx = session.beginTransaction();
			Query query = session.createQuery("from edu.intprog.egreeting.beans.GreetingHistory where SENDER_EMAIL=:userEmail or RECIPIENT_EMAIL=:userEmail order by SENT_DATE");
			query.setString("userEmail", user.get_emailAddr());
			userHistory = (List<GreetingHistory>) query.list();
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			if (tx != null && tx.isActive())
				tx.rollback();
			//sql error - report it to the user
			Messages error = new Messages();
			error.set_errorMessage(e.getMessage());
			request.setAttribute("msgs", error);
			getServletContext().getRequestDispatcher("/messages.jsp").forward(request, response);
			return;
		}
		
		request.setAttribute("userHistory", userHistory);
		getServletContext().getRequestDispatcher("/greetingsHistory.jsp").include(request, response);
	}   	  	    
}